# Copyright (c) 2024, kaepyz@gmail.com and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document
from frappe.utils import flt, now


class TongtoolOrder(Document):
	def validate(self):
		"""验证订单数据"""
		if not self.order_items:
			frappe.throw("订单必须包含商品明细")
		
		# 自动设置同步时间
		if not self.last_sync_time:
			self.last_sync_time = now()
		
		# 计算订单汇总数据
		self.calculate_totals()
		
		# 更新匹配状态
		self.update_match_status()
		
		# 计算利润
		self.calculate_profit()
	
	def calculate_totals(self):
		"""计算订单汇总数据"""
		total_item_cost = 0
		total_shipping_cost = 0
		
		for item in self.order_items:
			if item.item_cost and item.quantity:
				total_item_cost += flt(item.item_cost) * flt(item.quantity)
			
			if item.shipping_cost and item.quantity:
				total_shipping_cost += flt(item.shipping_cost) * flt(item.quantity)
		
		self.total_item_cost = total_item_cost
		self.first_leg_cost = total_shipping_cost
	
	def update_match_status(self):
		"""更新匹配状态"""
		if not self.order_items:
			self.match_status = "未匹配"
			return
		
		matched_count = 0
		total_count = len(self.order_items)
		
		for item in self.order_items:
			if item.match_status == "已匹配":
				matched_count += 1
		
		if matched_count == 0:
			self.match_status = "未匹配"
		elif matched_count == total_count:
			self.match_status = "完全匹配"
		else:
			self.match_status = "部分匹配"
	
	def calculate_profit(self):
		"""计算利润"""
		try:
			# 收入
			revenue = flt(self.products_total_price)
			
			# 成本
			item_cost = flt(self.total_item_cost)
			shipping_cost = flt(self.first_leg_cost)
			platform_fee = flt(self.platform_fee)
			
			# 计算毛利润
			gross_profit = revenue - item_cost - shipping_cost - platform_fee
			self.gross_profit = gross_profit
			
			# 计算毛利率
			if revenue > 0:
				self.profit_margin = (gross_profit / revenue) * 100
			else:
				self.profit_margin = 0
				
		except Exception as e:
			frappe.log_error(f"计算利润失败 {self.order_id_code}: {str(e)}")
	
	def on_update(self):
		"""更新后处理"""
		# 更新同步状态
		if self.sync_status != "同步失败":
			self.sync_status = "已同步"
			self.last_sync_time = now()
	
	@frappe.whitelist()
	def refresh_costs(self):
		"""刷新成本信息"""
		try:
			for item in self.order_items:
				if item.erp_item_code:
					item.update_item_costs()
			
			self.calculate_totals()
			self.calculate_profit()
			self.save()
			
			frappe.msgprint("成本信息已刷新", title="刷新成功", indicator="green")
			
		except Exception as e:
			frappe.log_error(f"刷新成本失败 {self.order_id_code}: {str(e)}")
			frappe.throw(f"刷新成本失败: {str(e)}")
	
	@frappe.whitelist()
	def rematch_items(self):
		"""重新匹配商品"""
		try:
			matched_count = 0
			
			for item in self.order_items:
				if item.tongtool_sku:
					item.auto_match_erp_item()
					if item.match_status == "已匹配":
						matched_count += 1
			
			self.update_match_status()
			self.calculate_totals()
			self.calculate_profit()
			self.save()
			
			frappe.msgprint(
				f"重新匹配完成，成功匹配 {matched_count} 个商品",
				title="匹配完成",
				indicator="blue"
			)
			
		except Exception as e:
			frappe.log_error(f"重新匹配商品失败 {self.order_id_code}: {str(e)}")
			frappe.throw(f"重新匹配失败: {str(e)}")
	
	@frappe.whitelist()
	def sync_from_tongtool(self):
		"""从通途重新同步订单数据"""
		try:
			from tongtool_integration.api.orders import OrderAPI
			
			order_api = OrderAPI()
			order_data = order_api.get_order(self.order_id_code)
			
			if order_data:
				self.update_from_tongtool_data(order_data)
				self.save()
				frappe.msgprint("订单数据已重新同步", title="同步成功", indicator="green")
			else:
				frappe.throw("在通途中未找到该订单")
				
		except Exception as e:
			frappe.log_error(f"重新同步订单失败 {self.order_id_code}: {str(e)}")
			frappe.throw(f"重新同步失败: {str(e)}")
	
	def update_from_tongtool_data(self, order_data):
		"""从通途数据更新订单"""
		# 更新基本信息
		self.order_status = self.map_order_status(order_data.get('orderStatus'))
		self.paid_time = self.parse_timestamp(order_data.get('paidTime'))
		self.platform_fee = order_data.get('platformFee', 0)
		self.actual_total_price = order_data.get('actualTotalPrice', 0)
		
		# 更新原始数据
		self.raw_data = order_data
		
		# 更新订单明细
		self.update_order_items_from_data(order_data.get('orderDetails', []))
	
	def update_order_items_from_data(self, order_details):
		"""从通途数据更新订单明细"""
		# 创建现有商品的映射
		existing_items = {item.web_store_item_id: item for item in self.order_items if item.web_store_item_id}
		
		for detail in order_details:
			web_store_item_id = detail.get('webStoreItemId')
			
			if web_store_item_id in existing_items:
				# 更新现有商品
				item = existing_items[web_store_item_id]
				item.tongtool_sku = detail.get('goodsMatchedSKU') or detail.get('goodsSKU')
				item.transaction_price = detail.get('transactionPrice', 0)
				item.quantity = detail.get('quantity', 1)
				item.goods_detail_id = detail.get('goodsDetailId')
				
				# 重新匹配
				if item.tongtool_sku and not item.erp_item_code:
					item.auto_match_erp_item()
	
	def map_order_status(self, status):
		"""映射订单状态"""
		status_mapping = {
			'waitPacking': '等待配货',
			'waitPrinting': '等待打印',
			'waitingDespatching': '等待发货',
			'despatched': '已发货',
			'unpaid': '未付款',
			'payed': '已付款'
		}
		return status_mapping.get(status, status)
	
	def parse_timestamp(self, timestamp_str):
		"""解析时间戳"""
		if not timestamp_str:
			return None
		
		try:
			from datetime import datetime
			return datetime.strptime(timestamp_str, '%Y-%m-%d %H:%M:%S')
		except:
			return None
